package cn.wolfcode.web.interceptor;

import cn.wolfcode.transfer.domain.Employee;
import cn.wolfcode.transfer.util.RequiredPermission;
import cn.wolfcode.transfer.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        //获取session中存储的员工对象
        Employee my_employee = UserContext.getCurrentUser();
        //判断是否是超管
        if (my_employee.getAdmin()){
            return true;
        }
        //判断handler是否是hendlerMethod的实例(非静态资源皆是handierMethod的实例)
        if (handler instanceof HandlerMethod){
            //是则强转
            HandlerMethod method = (HandlerMethod) handler;
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            //获取权限表达式
            if (methodAnnotation==null){
                return true;
            }
            String expression = methodAnnotation.expression();
            List<String> expressions = UserContext.getExpressions();
            if (expressions.contains(expression)){
                return true;
            }else {
                //使用request不经过视图解析器
//                request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request,response);
                response.sendRedirect("/nopermission");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
